using Microsoft.AspNetCore.Http;
using Vin.Extension.Framework.Tools;
using Vin.Extension.JwtBearer.Extension;
using Vin.Extension.JwtBearer.Models;
using Vin.Extension.JwtBearer.Tool;
using Vin.Tool.Domain.ExceptionModel;

namespace Vin.Extension.Framework.Extension;

public static class HttpContextExtension
{
    public static async Task AddRepeatCacheAsync(this HttpContext context, string key = "",
        TimeSpan expireTime = default)
    {
        await VinJwtRepeatTool.SetAsync(key, context.GetRealUserId(), expireTime);
    }

    public static T GetTokenModel<T>(this HttpContext context, string? prefix = null)
        where T : VinJwtTokenModel
    {
        return VinSecurityTool.GetTokenModelByToken<T>(prefix) ?? throw new UnauthorizedException();
    }

    public static T? GetTokenModelOrNull<T>(this HttpContext context, string? prefix = null)
        where T : VinJwtTokenModel
    {
        return VinSecurityTool.GetTokenModelByToken<T>(prefix);
    }

    public static VinJwtTokenModel? GetVinJwtTokenModel(this HttpContext context, string? prefix = null)
    {
        return VinSecurityTool.GetTokenModelByToken<VinJwtTokenModel>(prefix);
    }
}